package top.tenebrous.yzl.im.context;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.TextMessage;
import top.tenebrous.yzl.im.contants.CommonConstants;
import top.tenebrous.yzl.im.entity.ImWebSocketProperties;
import top.tenebrous.yzl.im.enums.ChannelType;
import top.tenebrous.yzl.im.enums.MessageType;
import top.tenebrous.yzl.im.factory.colony.MessageQueueFactory;
import top.tenebrous.yzl.im.listener.ReceiverMessageHandler;
import top.tenebrous.yzl.im.message.MessageBody;
import top.tenebrous.yzl.im.sender.AbstractSenderHandler;
import top.tenebrous.yzl.im.utils.WebSocketUtils;

import java.util.Objects;

/**
 * @author yazhang6
 */
@Slf4j
@Component
public class ImSenderImpl implements ImSender{

    @Autowired
    private ImWebSocketProperties webSocketProperties;

    @Autowired
    private ReceiverMessageHandler receiverMessageHandler;

    @Autowired
    private MessageQueueFactory messageQueueFactory;

    @Override
    public void send(MessageType messageType, MessageBody messageBody) {
        String message = WebSocketUtils.buildTextMessage(messageType.getCode(), messageBody);
        log.info("{} 发送消息开始:{}", CommonConstants.LOG_PREFIX, message);
        // 判断单机还是集群
        if (webSocketProperties.isEnableColony()) {
            // 如果是集群  获取集群共享模式
            AbstractSenderHandler instance = messageQueueFactory.getProducerInstance(webSocketProperties.getColonyShareType());
            if (Objects.isNull(instance)) {
                log.error("{}集群模式下, 未注册[{}]类型的消息发送者, 请检查是否有相关实现已经实现AbstractSenderHandler接口", CommonConstants.LOG_PREFIX, webSocketProperties.getColonyShareType());
                throw new RuntimeException("集群模式下, 未注册[" + webSocketProperties.getColonyShareType() + "]类型的消息发送者, 请检查是否有相关实现已经实现AbstractSenderHandler接口");
            }
            instance.broadcastMessage(null, new TextMessage(message));
        } else {
            // 单机模式
            log.info("{} 单机模式下发送消息", CommonConstants.LOG_PREFIX);
            receiverMessageHandler.handlerMessage(message, ChannelType.SEND_CHANNEL.getCode());
        }
    }

}
